package com.minhua.jijiehao2.mainframe.launcher.loginactivity.impl

import com.minhua.jijiehao2.base.BaseMvpPresenter
import com.minhua.jijiehao2.bean.BaseBean
import com.minhua.jijiehao2.bean.LoginBean
import com.minhua.jijiehao2.bean.PhoneVerifyBean
import com.minhua.jijiehao2.constants.DefineKey
import com.minhua.jijiehao2.constants.HttpConst
import com.minhua.jijiehao2.http.CallBack
import com.minhua.jijiehao2.http.ParamsMap
import com.minhua.jijiehao2.mainframe.launcher.loginactivity.imp.ILoginPresenter
import com.minhua.jijiehao2.mainframe.launcher.loginactivity.imp.ILoginView
import com.minhua.jijiehao2.utils.InputUtils
import com.minhua.jijiehao2.utils.encryption.MDUtil

internal class LoginPresenter : BaseMvpPresenter<ILoginView>(), ILoginPresenter {
    private var mLoginModel: LoginModel = LoginModel()

    override fun isPhoneExists() {
        val userName = v?.getUserName() ?: ""
        val password = v?.getPassword() ?: ""
        if (!InputUtils.checkCellphone(userName)) {
            v?.onUserNameError()
            return
        }
        if (!InputUtils.checkPassword(password)) {
            v?.onPasswordError()
            return
        }
        val map = ParamsMap()
        map.put(DefineKey.PHONE, userName)
        mLoginModel.isExists(map, object : CallBack<PhoneVerifyBean>() {
            override fun onSuccess(t: BaseBean<PhoneVerifyBean>) {
                val data = t.data
                val exists = data?.isExists
                if (HttpConst.STATE_10 == exists) {
                    v?.loginSuccess(exists)
                } else {
                    map.clear()
                    map.put(DefineKey.LOGIN_PHONE, userName)
                    map.put(DefineKey.LOGIN_PASSWORD, MDUtil.encode(MDUtil.TYPE.MD5, password))
                    map.put(DefineKey.SIGN_MSG, MDUtil.encode(MDUtil.TYPE.MD5,
                            DefineKey.APP_KEY + userName + MDUtil.encode(MDUtil.TYPE.MD5, password).toUpperCase()))
                    mLoginModel.login(map, object : CallBack<LoginBean>() {
                        override fun onSuccess(t: BaseBean<LoginBean>) {
                            mLoginModel.saveLogin(t.data!!)
                            v?.loginSuccess(HttpConst.STATE_20)
                        }
                    })
                }
            }

        })
    }


}